#include <stdio.h>
#include <string.h>
#include <time.h>
#include "sqlite3.h"
#define DBNAME "test.db"
int main()
{
	int i = 0;
	int rc = 0;
    char szSQL[1024];
	char szName[50], szDate[50];
	char *zErrMsg;
    sqlite3 *pdb;
	sqlite3_stmt *pstmt;
	// 打开数据库
    rc = sqlite3_open(DBNAME, &pdb);
    if (rc != SQLITE_OK)
    {
        sqlite3_close(pdb);
        printf("无法打开数据库%s\n", DBNAME);
    }
	//	建表	
	rc = sqlite3_exec(pdb,"create table user(id int,name Text, birthday Text)",0,0,&zErrMsg); 
    if (rc != SQLITE_OK)
    {
        sqlite3_close(pdb);
        printf("无法创建表%s\n", DBNAME);
    }

	time_t t1, t2;

    time(&t1);

    // 开启事务
    rc = sqlite3_exec(pdb, "BEGIN TRANSACTION;", NULL, NULL, NULL);
    if( rc != SQLITE_OK )
    {
         printf("BEGIN TRANSACTION: %s\n", sqlite3_errmsg(pdb));
         sqlite3_close(pdb);
         return -1;
    }

    // 使用绑定变量插入100万条数据
    sprintf(szSQL, "insert into user(id, name, birthday) values (?1, ?2, ?3);");

    // 预编译SQL
    rc = sqlite3_prepare(pdb, szSQL, strlen(szSQL), &pstmt, NULL);

    if (rc != SQLITE_OK)
    {
        printf("sqlite3_prepare: %s\n", sqlite3_errmsg(pdb));
        sqlite3_finalize(pstmt);
        sqlite3_close(pdb);
        return -1;
    }

    for (i = 0; i < 1000000; i++)
    {
        sqlite3_bind_int(pstmt, 1, i + 1);
        if( rc != SQLITE_OK ) 
        {
            printf("sqlite3_bind_int(%d): %s\n", rc, sqlite3_errmsg(pdb));
            return -1;
        }
        sprintf(szName, "%s%d", "zhangshan", i + 1);
        sqlite3_bind_text(pstmt, 2, szName, strlen(szName), NULL);
        if( rc != SQLITE_OK ) 
        {
            printf("sqlite3_bind_text (%d): %s\n", rc, sqlite3_errmsg(pdb));
            return -1;
        }
        sprintf(szDate, "%s", "2011-09-01 23:59:59");
        rc = sqlite3_bind_text(pstmt, 3, szDate, strlen(szDate), NULL);
        if( rc != SQLITE_OK ) 
       	{
            printf("sqlite3_bind_text(%d): %s\n", rc, sqlite3_errmsg(pdb));
            return -1;
       }
       rc = sqlite3_step(pstmt);
       if( (rc != SQLITE_OK) && (rc != SQLITE_DONE) && (rc != SQLITE_ROW) ) 
       {
           printf("sqlite3_step(%d): %s\n", rc, sqlite3_errmsg(pdb));
           return -1;
       }
       rc = sqlite3_reset(pstmt);
       if( rc != SQLITE_OK ) 
       {
           printf("sqlite3_reset(%d): %s\n", rc, sqlite3_errmsg(pdb));
           return -1;
       }
	}
	sqlite3_finalize(pstmt);
    // 提交事务
	rc = sqlite3_exec(pdb, "COMMIT TRANSACTION;", NULL, NULL, NULL);
    if( rc != SQLITE_OK )
    {
		printf("COMMIT TRANSACTION: %s\n", sqlite3_errmsg(pdb));
		sqlite3_close(pdb);
		return -1;
    }
    time(&t2);
    printf("耗时： %ld 秒\n", t2 - t1);
     // 关闭数据库
    sqlite3_close(pdb);
    return 0;
}

